package com.fm.financemanage.exception;


import com.fm.financemanage.constant.AppHttpCodeEnum;
import com.fm.financemanage.response.Callback;
import com.fm.financemanage.response.JsonData;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@Order(1)
@ControllerAdvice
@Component
public class AllAdminExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(AllAdminExceptionHandler.class);

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonData constraintViolationCatch(ConstraintViolationException c) {
        Set<ConstraintViolation<?>> constraintViolations = c.getConstraintViolations();
        String s = constraintViolations.stream().map(ConstraintViolation::getMessageTemplate).reduce((m1, m2) -> m1 + "," + m2).orElse("缺少必要参数");
        return Callback.fail("400", s);
    }

    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public JsonData exceptionDispose(ShiroException e) {

        // 返回給用戶的異常
        if (e instanceof UnauthorizedException) {
            return Callback.fail(AppHttpCodeEnum.NO_OPERATOR_AUTH.getCode() + "", AppHttpCodeEnum.NO_OPERATOR_AUTH.getErrorMessage());
        }
        // 返回給用戶的異常
        if (e instanceof UnknownAccountException) {
            return Callback.fail(AppHttpCodeEnum.ACCOUNT_ERROR.getCode() + "", AppHttpCodeEnum.ACCOUNT_ERROR.getErrorMessage());
        }
        // 返回給用戶的異常
        if (e instanceof IncorrectCredentialsException) {
            return Callback.fail(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getCode() + "", AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getErrorMessage());
        }
        return Callback.fail(AppHttpCodeEnum.UNEXCEPTION.getCode() + "", AppHttpCodeEnum.UNEXCEPTION.getErrorMessage());
    }

    /**
     * 非法参数异常
     */
    @ResponseBody
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonData illegalArgumentExceptionHandler(IllegalArgumentException e) {
        e.printStackTrace();
        return Callback.fail("700", "非法参数异常");
    }

}
